/*
 * @Author: Broin
 * @Date: 2021-12-29 09:42:58
 * @LastEditTime: 2022-01-04 22:35:00
 * @LastEditors: your name
 * @Description: 
 * @FilePath: /ac_interface/src/api/vm.js
 * MADE BY BROIN
 */

import VirtualMachine from '../utils/virtualMachine';
import { virtualMachines } from '../data/vm';
import SSH from '../utils/ssh';

/**
 * @description 添加一台虚拟机
 * @param {} name 
 * @param {*} IP 
 * @param {*} vmnormalpass 
 * @param {*} vmrootpass 
 * @param {*} type 
 * @returns 
 */
export function addMachine(name, IP, vmnormalpass, vmrootpass, type){
    let newMachine = new VirtualMachine(name, IP, vmnormalpass, vmrootpass, type);
    virtualMachines[virtualMachines.length] = newMachine;
    return 0;
}

/**
 * @description 通过虚拟机名查找一个虚拟机
 * @param {} name 
 * @returns 
 */
 export function findTerminalbyName(name) {
    for (let i = 0; i < virtualMachines.length; i++) {
        if (virtualMachines[i].name == name) {
            return i;
        }      
    }
    alert("没有这个虚拟机" + name);
    return -1;
}

export function listAllTerminalbyType(type) {
    let list = [];
    for (let i = 0; i < virtualMachines.length; i++) {
        if (virtualMachines[i].type == type) {
            list.push({name: virtualMachines[i].name});
        }
    }
    console.log('打印所有该角色虚拟机：' + list );
    return list;
}

/**
 * @description 通过虚拟机名删除一个虚拟机
 * @param {} name 
 * @returns 
 */
export function delMachine(name) {
    let index = findTerminalbyName(name);
    if(index == -1){
        console.log('没有这个名称');
        return -1;
    }
    let temp = virtualMachines[index];
    virtualMachines[index] = virtualMachines[virtualMachines.length - 1];
    virtualMachines[virtualMachines.length - 1] = temp;
    virtualMachines.pop();
    return 0;
}

/**
 * @description 建立ssh连接
 * @param {*} name 虚拟机名称
 * @param {*} vmrole 用户登录权限(root : normal)
 * @param {*} username 用户名(root : username(ex: yzc))
 */
export function connect(name, vmrole, username){
    let index = findTerminalbyName(name);
    if(vmrole == 'normal'){
        virtualMachines[index].ssh = new SSH(virtualMachines[index].IP, 22, username, virtualMachines[index].vmnormalpass);
    }
    else if(vmrole == 'root'){
        virtualMachines[index].ssh = new SSH(virtualMachines[index].IP, 22, username, virtualMachines[index].vmnormalpass);
    }
    //virtualMachines[index].ssh.createSSH();
    return 0;
}

/**
 * @description 执行命令
 * @param {*} name 虚拟机名称
 * @param {*} cmd 命令
 * @returns 
 */
export function shellCode(name, cmd){
    let index = findTerminalbyName(name);
    let data = virtualMachines[index].ssh.command(cmd);
    return {
        code: 0,
        data: data
    };
}

